package android.tusnotas.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.tusnotas.activities.extras.ShowCourseActivityExtras;
import android.tusnotas.beans.Course;
import android.tusnotas.beans.News;
import android.tusnotas.core.NewsAnalyser;
import android.tusnotas.model.TusNotasModel;
import android.tusnotas.services.WebCheckerManager;
import android.tusnotas.util.AlertBuilder;
import android.tusnotas.util.Properties;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ShowNews extends Activity {

	private ProgressDialog pd;
	private Thread thread = null;
	
	private List<News> newsList;
	private Course course = null;
	private TusNotasModel tusNotasModel = null;
	private String errorMessage = null;
	private Menu menu = null;
	private KillReceiver mKillReceiver;
	private WebCheckerManager webCheckerManager = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mKillReceiver = new KillReceiver();
		IntentFilter intentFilter = new IntentFilter("kill");
		registerReceiver(mKillReceiver,	intentFilter);
		
		setContentView(R.layout.show_news);
		setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		tusNotasModel = TusNotasModel.getTusNotasModel(getApplicationContext());
		webCheckerManager = new WebCheckerManager(this);
		
		initilizeThread();
		this.thread.start();
	}
		
	private void initilizeThread(){	
		pd = ProgressDialog.show(this, 
				getResources().getString(R.string.process_dialog_title_loading),
				getResources().getString(R.string.process_dialog_message_loading),
				Boolean.TRUE, Boolean.FALSE);
		this.thread = new Thread( new Runnable() {
			@Override
			public void run() {
				dataLoader(getIntent());
				pd.dismiss();
				h.sendEmptyMessage(0);
			}
		});
	}
	
	final Handler h = new Handler(){
	    public void handleMessage(Message msg) {
	        drawList();
	    }           
	};
	
	public void drawList(){
		List<String> datos = new ArrayList<String>();
		
		if(this.errorMessage != null){
			datos.add(this.errorMessage);
		}else if(this.newsList.size() == 0){
			datos.add(getString(R.string.message_no_news));
		}else{
			for(News news: this.newsList){
				if(news != null){
					datos.add(news.getTitle()+" - "+news.getDate()+"\n"+news.getContent()+"\n\n");
				}
			}
		}
		 
		ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,
		        android.R.layout.simple_list_item_1, datos);
		 
		ListView lstOpciones = (ListView)findViewById(R.id.LstOpciones);
		 
		lstOpciones.setAdapter(adaptador);
	}
	
	//gets data from db
	private Integer dataLoader(Intent intent){
		
		Integer courseId = intent.getIntExtra(ShowCourseActivityExtras.COURSE_ID, -1);
		intent.removeExtra(ShowCourseActivityExtras.COURSE_ID);
		if (courseId == -1) {
			return courseId;
		}
		this.course = tusNotasModel.selectCoursesById(courseId);
		
		NewsAnalyser newsAnalyser = new NewsAnalyser();
		try {
			this.newsList = newsAnalyser.doGetNews(course.getIdAula());
		} catch (Exception e) {
			this.errorMessage = getString(R.string.message_error_news); 
		}
		return 1;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.configuration:
			Intent welcomeIntent = new Intent(this, Login.class);
			startActivity(welcomeIntent);
			return Boolean.TRUE;

		case R.id.refresh:
			// refresh(Boolean.TRUE);
			Toast t2 = Toast.makeText(getApplicationContext(),R.string.toast_refresh, Toast.LENGTH_SHORT);
			t2.setGravity(Gravity.CENTER, 0, 0);
			t2.show();
			return Boolean.TRUE;

		case R.id.about:
			AlertBuilder.showAboutInfo(this);
			return Boolean.TRUE;
			
		case R.id.logout:
			
			// delete old hash
			TusNotasModel.getTusNotasModel(getApplicationContext()).updateProperty(Properties.HASH, "");
			Log.e(getClass().getName(),"Deleted saved hash");
			
			AlertBuilder.logout(this);
			return Boolean.TRUE;
			
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu myMenu) {
		menu = myMenu;
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		if (webCheckerManager.isWebCheckerStarted()) {
			inflater.inflate(R.menu.menu_instances_started, menu);
		} else {
			inflater.inflate(R.menu.menu_instances_stopped, menu);
		}
		return Boolean.TRUE;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mKillReceiver);
	}

	private final class KillReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }
}
